import Config from "../main.config";
import {getStorageSync, setStorageSync} from "../utils/Storage";
import {queryToString} from "../utils/Util"
const requestRecord = {}; //请求记录栈  防重复
const requestExpired = {}; //请求登录过期栈
const requestNetworkErr = {}; //请求网络错误栈
let isExpired = false; //是否过期
/*
* 获取请求名
* */
function _getRequestName (params) {
    let str = "";
    let {url = "", data = {}} = params;
    if (Object.keys(data).length > 0) {
        for (let i in data) {
            str += (i + "=" + data[i] + "&")
        }
        str = str.substr(0, str.length - 1);
    }
    if (url.indexOf("?") === -1) {
        return str ? (url + "?" + str) : url
    } else {
        return str ? (url + "&" + str) : url
    }
}



const Request = {
    /*
    * 请求
    * url不存在判断
    * 重复请求控制
    * token过期控制
    * */
    request: function (params) {
        const that = this;
        return new Promise(function (resolve, reject) {
            let {url, header = {"Content-type": "application/x-www-form-urlencoded"}} = params,
                token = getStorageSync(Config.storage.token);
            let requestName = _getRequestName(params); //设置请求唯名称
            if (!url) {reject(new Error("request.url is not found"))} //url 不存在
            if (requestRecord[requestName]) {return false}; //重复请求控制
            token ? header.Authorization = token : null;
            params.header ? params.header = Object.assign(params.header, header) : null;
            Object.keys(header).length > 0 ? params.header = header : null;
            requestRecord[requestName] = wx.request({
                ...params,
                success: async function (res) {
                    try {
                        let newRes = await that._dataSetting(res.data);
                        newRes ? resolve(res.data.code !== 0 ? res.data.data : res.data) : reject(res.data);
                    } catch (e) {
                        reject(e);
                    }
                },
                fail: function (err) {
                    requestNetworkErr[requestName] = params
                    reject(err);
                },
                complete: function () {
                    delete requestRecord[requestName];
                }
            })
        })
    },

    /*
    * 终止请求
    * */
    abort: function (params) {
        let requestName = _getRequestName(params); //设置请求唯名称
        if (requestRecord[requestName]) {
            requestRecord[requestName].abort();
            delete requestRecord[requestName]
        }
    },

    /*
    * 数据处理
    * */
    _dataSetting: async function (data) {
        if (data.code === 1502) { //token过期
            await this._showModal();
            const App = getApp();
            if (!App.globalData.isLoginExpired) {
                // const pages = getCurrentPages();
                // let currentContext = pages[pages.length - 1];
                // let currentRoute = currentContext.route;
                // let params = currentContext.options;
                // App.globalData.isLoginExpired = true;
                // setStorageSync(Config.storage.loginExpiredPage, "/" + currentRoute + queryToString(params))
                wx.redirectTo({ //关闭当前页面 跳转登录页
                    url: "/pages/login/index/index",
                    complete: function () {
                        App.globalData.isLoginExpired = false
                    }
                });
            }
            return false
        } else if (data.code !== 0 && data.code !== 200) {
            return false
        }
        return true
    },

    /*
    * 提示
    * */
    _showModal() {
        return new Promise(function (resolve) {
            wx.showModal({
                title: "提示",
                content: "需登录后访问，请先登录。",
                showCancel: false,
                complete: function () {
                    resolve()
                }
            })
        })
    }
}

module.exports = Request